package com.dongdongshop.controller;

import cn.hutool.json.JSONUtil;
import com.dongdongshop.data.Result;
import com.dongdongshop.dto.UserDTO;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.util.JwtUtil;
import com.dongdongshop.util.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    public Result login(@RequestParam String username, @RequestParam String password){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,password);
        try {
            subject.login(usernamePasswordToken);
        }catch (UnknownAccountException e1){
            return Result.RESPOSE(ResultEnum.UNKNOW_USER_NAME_PASSWORD);
        }catch (IncorrectCredentialsException e2){
            return Result.RESPOSE(ResultEnum.UNKNOW_USER_NAME_PASSWORD);
        }
        //单点登陆 客户端保存登录状态
        UserDTO userDTO =(UserDTO) SecurityUtils.getSubject().getPrincipal();
        LoginUser loginUser = new LoginUser();
        loginUser.setUserId(userDTO.getId().toString());
        loginUser.setUserName(userDTO.getUsername());
        //加密
        String token = jwtUtil.createJwt(loginUser.getUserId(), JSONUtil.toJsonStr(loginUser),"loginUser");
        return Result.OK().setData(token);
    }
}
